package com.witframework.meta.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.witframework.PropertiesConstants;
import com.witframework.core.ApplicationProperties;
import com.witframework.meta.MetaApp;
import com.witframework.meta.service.MetaAppService;
import com.witframework.web.mvc.Controller;
import com.witframework.web.mvc.WebContext;

@Component
public class MetaAppController implements Controller{

	@Autowired
	private MetaAppService metaAppService;
	
	@SuppressWarnings("unchecked")	
	public String executor(WebContext webContext) {		
		List<MetaApp> appList = metaAppService.pagedQuery(webContext.getFilter(),webContext.getPageSortModel("app"));
		webContext.setAttribute("appList",appList);
		webContext.addFootmark("app_list","应用");
		return WebContext.domainView("view/MetaApp/index.jsp");
	}
	public String edit(WebContext webContext){
		String[] ids=webContext.getSelItemList();
		if(ids!=null&&ids.length>0){
			MetaApp app=(MetaApp) metaAppService.get(ids[0]);
			webContext.setAttribute("app", app);
		}else{
			webContext.addNavigateTrace("app_edit","增加应用");
		}
		return WebContext.domainView("view/MetaApp/update.jsp");
	}

	public String store(WebContext webContext) {
		MetaApp app=new MetaApp();
		webContext.bindObject(app,"app_");		
		app.generateRefCodeAndOther();
		app.setDateType("USER");		
		webContext.validateObject("app", app,"//update.jsp");		
		metaAppService.saveOrUpdate(app);
		webContext.setPageInfo("操作成功");
		webContext.setPageScript("window.parent.frames.menu.refreshTree();");
		String target=webContext.getTraceNavigate("app_edit");
		webContext.sendRedirect(target==null?"/metaAppController"+ApplicationProperties.getProperty(PropertiesConstants.WIT):target);
		return null;
		
	}
	public String delete(WebContext webContext){
		String errormsg="";
		int deleted=0;
		String[] items=webContext.getSelItemList();
		for(String id:items){
			MetaApp app=(MetaApp)metaAppService.get(id);
			if(app.getModules().size()>0)
				errormsg=errormsg+" "+app.getName();
			else{
				metaAppService.deleteById(id);
				deleted++;
			}				
		}	
		String msg="";
		if(deleted>0)	
			msg+="成功删除:"+deleted+"条数据.";
		if(errormsg.length()>0)
			msg+="由于存在子模块，有些数据不能删除.";		
		if(errormsg.length()>0)
			webContext.setPageError(msg+"<script>window.parent.frames.menu.refreshTree();</script>");
		else
			webContext.setPageInfo(msg+"<script>window.parent.frames.menu.refreshTree();</script>");
		return "redirect://this";
	}
	public void setMetaAppService(MetaAppService metaAppService) {
		this.metaAppService = metaAppService;
	}
	
	
}
